﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Transactions;
using PagedList;
using Sovigaz.DataProvider;
using Utilities;

namespace Sovigaz.Permission.Repositories
{
    public class ProductMovementRepository : GenericRepository
    {
        public ProductMovementRepository()
            : base("InOutLineID")
        {
        }

        public ICollection<ProductMovementComplex> ProductMovements { get; set; }

        public ProductMovementRepository Getlist(string whereClause, string orderBy, string orderDirection, int pageNumber)
        {
            var query = _context.InOutLines
                .Join(_context.Products, i => i.ProductID, p => p.ProductID, (i, p) => new { i, p })
                .Join(_context.InOuts, ip => ip.i.InOutID, io => io.InOutID, (ip, io) => new ProductMovementComplex
                {
                    InOutLineID = ip.i.InOutLineID,
                    ProductID = ip.i.ProductID,
                    PartnerID = ip.i.PartnerID,
                    Barcode = ip.p.Barcode,
                    ProductCode = ip.p.ProductCode,
                    PartnerName = _context.Partners.FirstOrDefault(pa => pa.PartnerID == ip.i.PartnerID).PartnerName,
                    LocationName = _context.Partners.FirstOrDefault(pa => pa.PartnerID == ip.p.PartnerID).PartnerName,
                    Expired = ip.p.Expired,
                    DateFrom = io.Date,
                    DateTo = _context.InOutLines.Where(t => t.InOutLineID > ip.i.InOutLineID && t.ProductID == ip.i.ProductID)
                    .Join(_context.InOuts, t1 => t1.InOutID, t2 => t2.InOutID, (t1, t2) => new
                    {
                        Date = t2.Date,
                    })
                    .FirstOrDefault().Date,
                    IsDeleted = ip.i.IsDeleted,
                    Type = io.Type
                })
                .Where(whereClause)
                .OrderBy(t=>t.Barcode).ThenByDescending(t=>t.DateFrom)
                //.OrderBy(String.Format("{0} {1}", orderBy.Trim(), orderDirection.Trim()))
                .ToPagedList(pageNumber, DefaultPageSize);
            TotalItemCount = query.TotalItemCount;
            TotalItemOnPage = query.Count;
            PageCount = query.PageCount;
            PageNumber = query.PageNumber;
            ProductMovements = query.ToList();
            return this;
        }

    }
}
